﻿#region 文件信息

/*----------------------------------------------------------------
//
// 文件名称：
// 文件功能描述：
// 设计要求：
//
// 文 件 名：    RoleManagerViewModel
// 创建者：      杨程
// 创建日期：	    2022/12/20 15:06:51

//----------------------------------------------------------------*/

#endregion

namespace Vampirewal.Admin.Server.ViewModels.ViewModel.OrganizationManager;

/// <summary>
/// 角色管理页VM
/// </summary>
[VampirewalIoCRegister(ServerViewModelKeys.RoleManagerViewModel)]
public partial class RoleManagerViewModel : BillListBaseVM<Sys_RoleTemplate, Sys_RoleTemplate>
{
    /// <summary>
    ///
    /// </summary>
    public RoleManagerViewModel( IVampirewalCoreDialogMessage dialog, SqlSugarRepository<Sys_RoleTemplate> _repRole, SqlSugarRepository<Sys_RoleTemplate> _repSearch) : base(dialog, _repRole, _repSearch)
    {
        //构造函数

        OrgList.LoadFullNodes(RepBill.Change<Sys_Org>().ToList(w => w.OrgType == 1 || w.OrgType == 0));

        TreeListViewActionsCommand = new IVampirewalCoreEventCommand[]
        {
            new VampirewalCoreEventCommand("SelectedItemChanged","SelectedItem", new RelayCommand<GeneralTreeContainer<Sys_Org>>(Selected =>
            {
                var org = Selected.TreeNode;

            if (org.OrgType != 0)
            {
                //Queryable = repRole.AsQueryable().Where(w => w.TenantId == org.TenantId);

                GetPageList(w => !string.IsNullOrEmpty(w.BillId), o => new { o.CreateTime }, OrderByType.Asc, true);
            }
            }))
        };

        GetPageList(w => !string.IsNullOrEmpty(w.BillId), o => new { o.CreateTime }, OrderByType.Asc, true);
    }

    

    #region [     重写     ]

    protected override void InitVM()
    {
        OrgList = new TreeBuilderByFullLoad<Sys_Org>();
    }

    protected override IUcViewBase SetView()
    {
        switch (ViewKey)
        {
            case ServerViewKeys.EditRoleView:
                return WindowsManager.GetInstance().GetView(ViewKey);

            case ServerViewKeys.ConfigurePermissionView:
                return WindowsManager.GetInstance().GetView(ViewKey);

            default:
                throw new NotImplementedException();
        }
    }

    public override void ExecuteBeforeCloseDialogWindow(object obj)
    {
    }

    #endregion

    #region [     属性     ]

    /// <summary>
    /// 底部页面
    /// </summary>
    [ObservableProperty]
    public IUcViewBase bottomContext;

    public TreeBuilderByFullLoad<Sys_Org> OrgList { get; set; }

    public IVampirewalCoreEventCommand[] TreeListViewActionsCommand { get; set; }

    private string ViewKey;

    #endregion

    #region [     Command命令     ]

    #region [     分页命令     ]

    /// <summary>
    ///     页码改变命令
    /// </summary>
    public RelayCommand<FunctionEventArgs<int>> PageUpdatedCmd =>
        new Lazy<RelayCommand<FunctionEventArgs<int>>>(() =>
            new RelayCommand<FunctionEventArgs<int>>(PageUpdated)).Value;

    /// <summary>
    ///     页码改变
    /// </summary>
    private void PageUpdated(FunctionEventArgs<int> info)
    {
        EntityList.Clear();

        Page = info.Info;

        GetPageList(w => !string.IsNullOrEmpty(w.BillId), o => new { o.CreateTime }, OrderByType.Asc, true);
    }

    #endregion

    [RelayCommand]
    public void LookDetail(Sys_RoleTemplate user)
    {
        BottomContext = WindowsManager.GetInstance().GetView(ServerViewKeys.EditRoleView, Param: user);
    }

    [RelayCommand]
    public void ConfigurePermissions(Sys_Org org)
    {
        var adminRole = RepBill.Single(s => s.TenantId == org.TenantId && s.IsAdmin);

        ViewKey = ServerViewKeys.ConfigurePermissionView;

        SetDialogWindowSetting(new DialogWindowSetting()
        {
            WindowWidth = 800,
            WindowHeight = 600,
            IsShowMaxButton = false,
            IsShowMinButton = false,
            IsOpenWindowSize = false,
            TitleFontSize = 15,
            CloseDialogWindowCallBackCommand = new RelayCommand<object>(ExecuteBeforeCloseDialogWindow),
            IconStr = "pack://application:,,,/Vampirewal.Admin.Server;component/Logo.png"
        });

        ExecuteShowDialogWindow(adminRole);
    }

    #endregion
}

/// <summary>
/// 编辑角色VM
/// </summary>
[VampirewalIoCRegister(ServerViewModelKeys.EditRoleViewModel)]
public partial class EditRoleViewModel : BillVM<Sys_RoleTemplate>
{
    private IVampirewalCoreDialogMessage Dialog { get; set; }

    public EditRoleViewModel(IVampirewalCoreDialogMessage dialog, SqlSugarRepository<Sys_RoleTemplate> _repRole) : base(_repRole)
    {
        Dialog = dialog;
    }
}

[VampirewalIoCRegister(ServerViewModelKeys.ConfigurePermissionViewModel)]
public partial class ConfigurePermissionViewModel : BillVM<Sys_RoleTemplate>
{
    //private SqlSugarRepository<Sys_RoleTemplate> repRole { get; set; }

    private IVampirewalCoreDialogMessage Dialog { get; set; }

    public ConfigurePermissionViewModel(IVampirewalCoreDialogMessage dialog, SqlSugarRepository<Sys_RoleTemplate> _repRole) : base(_repRole)
    {
        //repRole = _repRole;
        Dialog = dialog;

        Title = "分配菜单和按钮权限";
    }

    public override void InitData()
    {
        MenuList = new TreeBuilderByFullLoad<Sys_Menu>();
    }

    public override void BillVmInitData()
    {
    }

    public override void PassData(object obj)
    {
        var model = obj as Sys_RoleTemplate;

        if (model != null)
        {
            SetEntity(model);

            #region 获取数据

            var AllMenu = Rep.Change<Sys_Menu>().ToList(s => s.IsActive);
            MenuList.LoadFullNodes(AllMenu);

            var EntityMenu = Rep.Change<Sys_RolePermission>().ToList(s => s.RoleId == Entity.BillId);

            foreach (var item in AllMenu)
            {
                //var menu= EntityMenu.FirstOrDefault(f => f.PermissionId == item.BillId);

                if (EntityMenu.Any(a => a.PermissionId == item.BillId && item.MenuType == 2))
                {
                    //item.IsChecked = true;
                    var node = MenuList.GetDisplayNodes().FirstOrDefault(w => w.TreeNode.Equals(item));
                    MenuList.CheckAndUpdateStateNode(node, true);
                }
            }

            #endregion
        }
        else
        {
            CloseView();
        }
    }

    protected override void CloseView()
    {
        WindowsManager.GetInstance().CloseDialogWindow(ViewId);
    }

    public override object GetResult()
    {
        return true;
    }

    public TreeBuilderByFullLoad<Sys_Menu> MenuList { get; set; }

    [RelayCommand]
    public void Save()
    {
        var selected = MenuList.GetDisplayNodes().Where(w => w.IsChecked == null || w.IsChecked == true).Select(s => s.TreeNode).ToList();

        try
        {
            Rep.BeginTran();

            Rep.Change<Sys_RolePermission>().Delete(d => d.RoleId == Entity.BillId);

            foreach (var item in selected)
            {
                Sys_RolePermission permission = new Sys_RolePermission()
                {
                    RoleId = Entity.BillId,
                    PermissionId = item.BillId,
                    CreateBy = "administrator",
                    CreateUserId = Guid.Empty.ToString()
                };

                Rep.Change<Sys_RolePermission>().Insert(permission);
            }

            Rep.CommitTran();

            CloseView();
        }
        catch (Exception ex)
        {
            Rep.RollbackTran();
        }
    }
}